package com.nervenets.web.controller.editor;

import com.alibaba.fastjson.JSONObject;
import com.nervenets.Global;
import com.nervenets.web.controller.BaseController;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.entity.ResponseResult;
import com.nervenets.web.service.WebSocketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.Set;
import java.util.UUID;

@Api(value = "网页编辑器接口v1", description = "网页编辑器相关接口")
@RestController
@RequestMapping("/api/v1/editor")
public class EditorController extends BaseController {
    @Resource
    private WebSocketService webSocketService;

    @ApiOperation("获取登录二维码")
    @PostMapping("/loginCode")
    public ResponseResult loginCode() {
        final String uuid = UUID.randomUUID().toString();
        globalService.setGlobalPair(uuid, uuid, 60);

        JSONObject object = new JSONObject();
        object.put("expired", 60);
        object.put("code", uuid);
        object.put("subscribe", String.format("/topic/%s", uuid));
        object.put("ws", String.format("https://%s/ws", Global.getApplicationProperties().getProperty("app.ws.domain")));
        return successMessage(object);
    }

    @ApiOperation("小程序二维码登录")
    @PostMapping("/login")
    public ResponseResult login(@RequestBody EditorLoginParams params) throws Exception {
        if (params.tokenIllegal()) return errorMessage(MessageCode.code_777);
        final Set<ConstraintViolation<EditorLoginParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        final String value = globalService.getGlobalPair(params.getUuid());
        if (null == value) return errorMessage(MessageCode.code_444, "该二维码已过期");
        globalService.delGlobalPair(params.getUuid());

        JSONObject object = new JSONObject();
        object.put("token", params.getToken());
        webSocketService.sendMessage(params.getUuid(), "login", object.toJSONString());

        return successMessage();
    }
}
